package com.tledu.controller;

import com.tledu.config.UploadProperty;
import com.tledu.core.Result;
import com.tledu.domain.User;
import com.tledu.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author cyrus
 */
@RestController
@AllArgsConstructor
public class LoginController {

    private final IUserService userService;

    private final UploadProperty uploadProperty;

    /**
     * 直接把session或者request当作参数写进来，Spring会自动注入当前的session或request
     */
    @PostMapping("/login")
    public Result<User> login(String username, String password, HttpSession session, HttpServletRequest req) {
        User user = userService.login(username, password);
        // 登录成功了记录session
        session.setAttribute("currentLoginUser", user);
        return Result.success(user);
    }

//    @PostMapping("/register")
//    public Result register(@RequestBody User user) {
//        return Result.success(userService.register(user));
//    }

    @PostMapping("/register")
    public Result<User> register(MultipartFile file, User user) {
        if (!file.isEmpty()) {
            // 代表用户上传了头衔
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            List<String> supportSuffix = Arrays.asList(".png", ".jpg");
            if (!supportSuffix.contains(suffix)) {
                return Result.error(500, "头像格式只支持，png和jpg！");
            }
            // 最终的文件名
            String filename = "avatar/"+System.currentTimeMillis()+"-" + originalFilename;
            try {
                file.transferTo(new File(uploadProperty.getLocalPath() + filename));
                user.setAvatar(filename);
            } catch (IOException e) {
                return Result.error(500, "头像上传失败，请联系管理员");
            }
        }
        userService.register(user);
        return Result.success(user);
    }

}
